import Schema from '@/plugins/async-validator'

export default {
  data () {
    return {
      // error message
      errorMessage: '',

      // 是否验证
      isValidate: false,
    }
  },

  props: {
    required: {
      type: Boolean,
      default: () => false,
    },
    rules: {
      type: Array,
      default: () => [],
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  },

  methods: {
    // 创建验证
    createSchema (option) {
      const descriptor = { formData: this.rules }
      const form = { formData: this.inputValue }
      const schema = new Schema(descriptor)

      return schema.validate(form, option)
    },

    // 表单验证
    validate (option = { first: true }) {
      return new Promise((resolve, reject) => {
        this.errorMessage = ''
        this.isValidate = false

        this.$nextTick(() => {
          if (this.canDo) {
            resolve(true)
            return false
          }

          this.createSchema(option)
            .then(() => {
              resolve(true)
            })
            .catch(({ errors: [{ message }] }) => {
              this.isValidate = true
              this.errorMessage = message
              reject({ message, dom: this.refCustomForm })
            })
            .finally(() => {
              this.$emit('validate')
            })
        })
      })
    },
  },
}
